package functions

import (
	"github.com/project-flogo/core/data/coerce"

	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/expression/function"
)

func init() {
	err := function.Register(&fnToMap{})
	if err != nil {
		panic(err)
	}
}

type fnToMap struct{}

func (fnToMap) Name() string {
	return "toMap"
}

func (fnToMap) Sig() (paramsTypes []data.Type, isVariadic bool) {
	return []data.Type{data.TypeObject}, true
}

func (fnToMap) Eval(params ...interface{}) (interface{}, error) {
	m := map[string]interface{}{}
	for _, param := range params {
		kv, err := coerce.ToObject(param)
		if err != nil {
			return nil, err
		}
		key, err := coerce.ToString(kv["key"])
		if err != nil {
			return nil, err
		}
		m[key] = kv["value"]
	}
	return m, nil
}
